/**
 * 选择成员组件扩展代码
 * eg：
 * 获取所有成员：inbiz('EformSelectMember_777685').value
 * 获取一个成员：inbiz('EformSelectMember_777685').value[0]
 * 清除成员：inbiz('EformSelectMember_777685').value = []
 * 赋值成员：d=inbiz('EformSelectMember_777685').value[0]
 *          inbiz('EformSelectMember_777685').value = [d]
 */
import { extendApi } from '@inbiz/utils';
import { MutableRefObject } from 'react';
import type { IProps } from './index';
import { getSaveValue } from './util';

export default extendApi((_events: MutableRefObject<IProps['callBackEvents']>, props: IProps) => {
  return {
    getText() {
      try {
        return props.value ? props.value.map((v) => v.name).join(',') : '';
      } catch (e) {
        console.error(e);
        return '';
      }
    },
    getSaveData: () => {
      return {
        value: props.value?.map((item: any) => getSaveValue(item, props.tabs.length > 1)).join(','),
        childData:
          props.storageConfig && props.childModelConfig
            ? {
                controlId: props.controlId,
                modelKey: props.storageConfig?.business,
                datas: [
                  ...props.value?.map((item: any) => {
                    return props.storageConfig?.tableData.reduce((pre: any, next: any) => {
                      pre[next.modelAttr] = item[next.componentAttr];
                      pre['_opt'] = 'add';
                      return pre;
                    }, {});
                  }),
                  {
                    _opt: 'del',
                  },
                ],
              }
            : undefined,
      };
    },
  };
});
